// components/calendar/calendar.ts
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    initDate: {
      type: String,
      value: ""
    },
    // dateArr: {
    //   type: Array,
    //   value: []
    // }
  },

  /**
   * 组件的初始数据
   */
  data: {
    date: "",
    dateArr: [],
    year: "",
    month: "",
    day: "",
    deliveryDays:1

  },
  attached() {

    this.init()

  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleClick(e) {
      const {
        index
      } = e.currentTarget.dataset
      const {deliveryDays} = this.data
      const isSelected = this.data.dateArr[index].isSelected
      const selectedArr = this.data.dateArr.filter(item => {
        return item.isSelected
      })

      if (selectedArr.length >= parseInt(deliveryDays) && !isSelected) {
        wx.showToast({
          title: `已选满${parseInt(deliveryDays)}天`,
          icon: 'error'
        })

      } else {
        this.setData({
          [`dateArr[${index}].isSelected`]: !isSelected
        })
        wx.setStorageSync('orderDateArr', this.data.dateArr)

      }
    },


    init() {
      const dateArr = wx.getStorageSync('orderDateArr')
      const deliveryDays = wx.getStorageSync('orderDeliveryDays')
      this.setData({
        deliveryDays
      })


      if (dateArr.length == 0) {
        const initDate = wx.getStorageSync('orderStartDate')
        const dateArr = initDate.split("-").map(item => {
          return parseInt(item)
        })

        const date = new Date(dateArr[0], dateArr[1] - 1, dateArr[2]);
        const arr = []
        let preMonth;
        // const arr = []
        for (let i = 0; i < deliveryDays+30; i++) {
          const dtime = date.getTime() + 1000 * 60 * 60 * 24 * i;
          const dateDate = new Date(dtime);
          const dateStr = `${dateDate.getFullYear()}年${dateDate.getMonth()+1}月`;
          const dateWeek = dateDate.getDay();
          const dateMonth = dateDate.getMonth() + 1;
          const dateDay = dateDate.getDate();
          const dateYear = dateDate.getFullYear();

          let isNewRow = false;

          if (i === 0) {
            isNewRow = true
            preMonth = dateMonth;
            arr.push({
              isNewRow,
              dateStr
            })
          }

          if (preMonth !== dateMonth) {
            isNewRow = true
            preMonth = dateMonth;
            arr.push({
              isNewRow,
              dateStr
            })
          }
          arr.push({
            dateWeek,
            dateMonth,
            dateDay,
            dateYear,
            isMarginItem: isNewRow,
            isSelected: false
          })
        }

        this.setData({
          dateArr: arr
        })

      } else {
        this.setData({
          dateArr
        })
      }

    }

  }
})